<template>
    <div>
        <Row style="margin: 5px 5px 0 5px">
            <i-col span="8"  >
                <Button type="primary" @click="btn_add_release" style="margin-right: 5px" v-has="'add_release'">创建发布</Button>
                <Button @click="btn_refresh" >刷新</Button>
            </i-col>
            <!-- 查询区域 -->
            <i-col span="8" >
                <Form ref="select_form" :model="select_item" :rules="select_rules"  inline>
                    <Form-Item  prop="project" >
                        <Select v-model="select_item.project" placeholder="先选择项目" style="min-width:100px" >
                            <Option v-for="project in project_list" :key="project" :value="project">{{ project }}</Option>
                        </Select>
                    </Form-Item>
                    <FormItem>
                        <Button type="primary"  @click="btn_select_release('select_form')">查询</Button>
                    </FormItem>
                </Form> 
            </i-col>
        </Row>
        <!-- 列表区域 -->
        <i-table border stripe  :columns="format" :data="show_list" height="720">
            <template slot-scope="{ row, index }" slot="action">
                <Button type="primary" class="button_class"  v-has="'edit_release'" v-if="allow_edit(index)"  @click="btn_edit_release(index)">编辑</Button>
                <Button type="primary" class="button_class"  v-has="'edit_release'" disabled v-else>编辑</Button>
                <Button v-if="allow_review(index)" type="primary" class="button_class" v-has="'review_release'" @click="btn_review(index)">评审</Button>
                <Button v-else type="primary" class="button_class" v-has="'review_release'" disabled>评审</Button>
                <Button v-if="allow_publish(index)" type="primary" class="button_class" v-has="'publish_release'" @click="btn_publish(index)">上线</Button>
                <Button v-if="allow_accept(index)" type="primary" class="button_class" v-has="'accept_release'" @click="btn_accept(index)">验收</Button>
                <Button type="error" class="button_class"  v-has="'delete_release'" @click="del_release(index)">删除</Button>
            </template>
        </i-table >
        <div style="text-align: center;margin-top: 10px;">
            <Page ref="page" :total="total" :page-size="pageSize"  @on-change="changePage" show-total/>
        </div>
        <!-- 创建发布模态框 -->
        <Modal v-model="show_add_release_modal" draggable  width="800">
            <p slot="header" style="color:#f60;text-align:center">
                <span>添加发布</span>
            </p>
            <div >
                <Form ref="release" :model="release" :rules="release_rules" label-position="left"  :label-width="120">
                   <Form-Item label="选择项目" prop="project">
                        <Select v-model="release.project" @on-change="project_change">
                            <Option v-for="project in project_list" :key="project" :value="project">{{ project }}</Option>
                        </Select>
                    </Form-Item> 
                    <FormItem label="选择服务" prop="service_list">
                        <CheckboxGroup v-model="release.service_list">
                            <Checkbox  v-for="service in service_list" :label="service" :key="service" :value="service">{{service}}</Checkbox>
                        </CheckboxGroup>
                    </FormItem>
                </Form> 
            </div>
            <div slot="footer">
                <Button type="primary" size="large"  @click="submit_add_release('release')">提交</Button>
            </div>
        </Modal>
        <!-- 编辑发布模态框 -->
        <Modal v-model="show_edit_release_modal" draggable  width="1000">
            <p slot="header" style="color:#f60;text-align:center;height:30px">
               <span>编辑发布内容</span>
            </p>
            <div >
                <Form ref="release_edit" :model="release_edit" :rules="release_rules" label-position="left"  :label-width="100" inline>
                    <Form-Item label="项目:" prop="project">
                        <Input v-model="release_edit.project" style="width:100px"  disabled />
                    </Form-Item> 
                    <Form-Item label="发布类型:" prop="type">
                        <Select v-model="release_edit.type"  style="width:100px" >
                            <template v-for="type in release_types" >
                                <Option :key="type" :value="type" v-if="type === release_edit.type"  selected>{{ type }}</Option>
                                <Option :key="type" :value="type" v-else>{{ type }} </Option>
                            </template>
                        </Select>
                    </Form-Item> 
                    <Form-Item label="状态:"  prop="status">
                        <Select v-model="release_edit.status"  style="width:100px" >
                            <template v-for="status in status_list" >
                                <Option :key="status" :value="status" v-if="status === release_edit.status"  selected>{{ status }}</Option>
                                <Option :key="status" :value="status" v-else>{{ status }} </Option>
                            </template>
                        </Select>
                    </Form-Item>
                    <br>
                    <FormItem label="选择服务:" prop="service_list">
                        <CheckboxGroup v-model="release_edit.service_list">
                            <template v-for="service in service_list" >
                                <Checkbox  :label="service" :key="service" :value="service" v-if="service in release_edit.service_list" checked>{{service}}</Checkbox>
                                <Checkbox :label="service" :key="service" :value="service" v-else>{{service}}</Checkbox>
                            </template>
                        </CheckboxGroup>
                    </FormItem>
                    <p style="margin:0 0 5px 80px;">已选: {{ release_edit.service_list.join(',') }}</p>


                    <Form-Item label="关联需求:"  prop="requirement">
                        <CheckboxGroup v-model="release_edit.requirements">
                            <template v-for="(requirement,key) in nf_requirement_list" >
                                <Checkbox  :label="requirement.id" :key="key" class="check_box_class"  v-if="release_edit.requirements!= null &&  requirement.id in release_edit.requirements" checked >{{ requirement.name.slice(0,20) }}</Checkbox>
                                <Checkbox :label="requirement.id" :key="key" class="check_box_class"  v-else >{{ requirement.name.slice(0,20) }} </Checkbox>
                            </template>
                        </CheckboxGroup>
                    </Form-Item> 
                    <Form-Item label="关联bug:"  prop="bug">
                       <CheckboxGroup v-model="release_edit.bugs">
                            <template v-for="(bug,key) in nf_bug_list" >
                                <Checkbox  :label="bug.id" :key="key" class="check_box_class"   v-if=" release_edit.bugs != null && bug.id in release_edit.bugs" checked > {{ bug.name.slice(0,20) }}</Checkbox>
                                <Checkbox :label="bug.id" :key="key"  class="check_box_class"   v-else >{{ bug.name.slice(0,20) }} </Checkbox>
                            </template>
                        </CheckboxGroup>
                    </Form-Item> 

                    <Form-Item label="描述:"  prop="description">
                        <Input type="textarea" v-model="release_edit.description" :autosize="{minRows: 3,maxRows: 100}"  style="overflow: auto;width: 800px" />
                    </Form-Item>

                    <Form-Item label="指派审核人:"  prop="leader">
                        <Select v-model="release_edit.review_user"  style="width:100px" >
                            <template v-for="leader in project_leader" >
                                <Option :key="leader" :value="leader" v-if="leader === release_edit.leader"  selected>{{ leader }}</Option>
                                <Option :key="leader" :value="leader" v-else>{{ leader }} </Option>
                            </template>
                        </Select>
                    </Form-Item>
                </Form> 
            </div>
            <div slot="footer" class="modal_footer">
                <Button type="primary" size="large"  @click="submit_edit_release('release_edit')">提交</Button>
            </div>
        </Modal>

        <!-- 评审模态框 -->
        <Modal v-model="show_release_review_modal" draggable  width="800">
            <p slot="header" style="color:#f60;text-align:center">
               <span>评审</span>
            </p>
            <div >
                <row >
                    <i-col span="12">
                        <p><span class="label_class">项目:</span> {{release_review.project}}  </p> 
                    </i-col>
                    <i-col span="12">
                        <p><span class="label_class">发布服务:</span> {{ release_review.service_list.join(',') }}</p>
                    </i-col>
                </row>

                <row >
                    <i-col span="12">
                        <p><span class="label_class">发布类型:</span> {{release_review.type}} </p>
                    </i-col>

                </row>
                <row >
                    <i-col span="12">
                        <p><span class="label_class">创建用户:</span>{{release_review.create_user}}  </p> 
                    </i-col>
                    <i-col span="12">
                        <p><span class="label_class">创建时间:</span> {{release_review.create_time}} </p>
                    </i-col>
                </row>
                <Divider />
                <row >
                    <i-col span="12">
                        <p><span class="label_class">关联需求:</span></p>
                        <div style="margin-left: 40px">
                            <template v-for="requirement in release_review.requirements">
                                <li :key="requirement.id">{{requirement.name}}</li>
                            </template>
                        </div>
                    </i-col>
                    <i-col span="12">
                        <p><span class="label_class">关联bug:</span></p>
                        <div style="margin-left: 40px">
                            <template v-for="bug in release_review.bugs">
                                <li :key="bug.id">{{bug.name}}}</li>
                            </template>
                        </div>
                    </i-col>
                </row>
                <br>

                <p><span class="label_class">描述:</span></p>
                <div style="margin-left: 40px">
                    <pre>{{ release_review.description }}</pre>
                </div>
                <Divider />
            </div>
            <Form  ref="review_form" label-position="left"  :label-width="80" inline>
                    <FormItem label="评审结果" >
                        <Select v-model="review_form.result" placeholder="选择评审结果" style="min-width:100px" >
                            <Option v-for="result in review_result" :key="result" :value="result">{{ result }}</Option>
                        </Select>
                    </FormItem>
                    <Form-Item label="评审意见:">
                        <Input type="textarea" v-model="review_form.content" :autosize="{minRows: 3,maxRows: 5}"  style="overflow: auto;width: 680px" />
                    </Form-Item> 
            </Form>
            <div slot="footer" class="modal_footer">
                <Button type="primary"  @click="submit_review('release_review')">提交评审</Button>
            </div>
        </Modal>

    </div>
</template>

<script>

import { release_add,
        release_list,
        release_delete,
        release_update,
        release_select,
        release_review,
        get_project_name_list,
        get_service_by_project,
        not_finished_bug,
        not_finished_requirement,
        release_detail,
        get_project_leader,
        release_update_status } from '@/api';

import { post } from '@/api/http'

import { show_simple_page,colors } from '@/common/util' 

// let release_status_dict = {
//     0: '创建',
//     1: '待审核',
//     2: '待发布测试',
//     3: '发布测试失败',
//     4: '发布测试成功',
//     5: '待发布生产',
//     6: '发布生产失败',
//     7: '上线完成'
// }
// let colors = {
//     'red': '#ed4014',
//     'green': '#19be6b',
//     'blue': '#2db7f5',
//     'yellow': '#ff9900',
//     'gray': '#515a6e',
//     'black': '#17233d',
// }
export default {
    data() {
        return {
            format: [
                {
                    title: '发布Id',key: 'id',
                    render: (h,params) => {
                        return h('div',[
                            h('a',{
                                style: {
                                    color: 'blue'
                                },
                                on: {
                                    click: ()=>{                    
                                        this.handleLink(params);
                                    }
                                }
                            },params.row.id)
                        ])
                    }
                },
                {
                    title: '项目',key: 'project'
                },
                {
                    title: '服务项',key: 'service_list',                    
                    render: (h,params) => {
                        let texts = '';
                        if(params.row.service_list == null){
                            texts = null
                        }else{
                            texts = params.row.service_list.join(',')
                        }
                        return h('div',{style:{'overflow':'auto',}}, [
                            h('p', texts)
                        ]);
                    }
                },
                {
                    title: '发布类型',key: 'type',
                },
                {
                    title: '关联需求',key: 'requirements',                   
                    render: (h,params) => {
                        let texts = '';
                        if(params.row.requirements == null){
                            texts = null
                        }else{
                            texts = params.row.requirements.join(',')
                        }
                        return h('div',{style:{'overflow':'auto',}}, [
                            h('p', texts)
                        ]);
                    },

                },
                {
                    title: '关联bug',key: 'bugs',
                    render: (h,params) => {
                        let texts = '';
                        if(params.row.bugs == null){
                            texts = null
                        }else{
                            texts = params.row.bugs.join(',')
                        }
                        return h('div',{style:{'overflow':'auto',}}, [
                            h('p', texts)
                        ]);
                    },
                },
                {
                    title: '描述',key: 'description',tooltip: true,ellipsis: true,
                },
                {
                    title: '创建用户',key: 'create_user'
                },
                {
                    title: '审核人',key: 'review_user',
                    render:(h,params) => {
                        let review_user = params.row.review_user
                        if (review_user == undefined){
                            return h('p','未指定')
                        }else {
                            return h('p',review_user)
                        }
                    }
                },
                {
                    title: '状态',key: 'status',
                    render:(h,params) => {
                        let status = params.row.status
                        if(status=='上线完成'){
                            return h('span',{
                                style: {
                                    color: colors['green'],
                                }
                            },status)
                        }else if (status=='待审核' ){
                            return h('span',{
                                style: {
                                    color: colors['yellow']
                                }
                            },status)
                        }else if (status=='发布生产失败'){
                            return h('span',{
                                style: {
                                    color: colors['red']
                                }
                            },status)
                        }else if (status=='待发布' || status=='待发布生产' || status=='待发布测试'){
                            return h('span',{
                                style: {
                                    color: colors['blue']
                                }
                            },status)
                        }else if (status=='重新修改' ){
                            return h('span',{
                                style: {
                                    color: colors['black']
                                }
                            },status)
                        }else {
                            return h('span',{},status)
                        }
                    }
                },
                {
                    title: '创建时间',key: 'create_time'
                },
                {
                    title: '操作',slot: 'action',width: 300,align: 'center'
                }
            ],
            // 新增站点绑定
            show_add_release_modal: false,
            release: {
                project: '',
                service_list: [],  
            },
            project_list: [],
            service_list: [],
            release_types : ['滚动更新','蓝绿部署','灰度发布'],
            release_rules: {
                project:[
                    {required: true,message:"请选择好项目",trigger: 'blur'},
                ],
            },
            
            // 编辑
            show_edit_release_modal:false,
            release_edit: {
                project: '',
                service_list: [],
                type: '',  
                requirements: [],
                bugs: [], 
                description: '',
                status:'',
                review_user: '',
            },
            status_list:['草稿','待审核','重新修改','撤销发布','待生产发布','生产发布失败','上线完成'],
            project_leader:'',
            // 审核
            show_release_review_modal:false,
            release_review: {
                project: '',
                service_list: [],
                type: '',  
                requirements: [],
                bugs: [], 
                description: '',
                status:'',
            },
            review_result: ['核准发布','打回重改','拒绝'],
            review_form: {
                result: '',
                content: '',
            },

            nf_requirement_list: [],
            nf_bug_list: [],

            // 查询数据
            select_item: {
              project: '',
            },
            select_rules:{
                project:[
                    { required: true,message:"请先选择项目",trigger: 'change'},
                ],  
            },
            show_list: [],
            // 分页
            total: 0,
            pageSize: 15,
        }
    },
    methods: {
        btn_refresh(){
            this.refresh()
        },
        handleLink(params){
            const { href } = this.$router.resolve({
                path: '/releaseDetail'
            });
            window.open(href+"?id="+params.row.id, '_blank');
        },
        btn_close_detail(){
            this.show_release_detail_modal= false
        },
        btn_accept(index){
            let id = this.show_list[index].id
            let data = {"id":id,"action":"accept"}
            post(release_update_status,data).then(response=>{
                let info = JSON.stringify(response.data)
                if(info.indexOf('ok')!= -1){
                    this.$Message.success("更新验收成功")
                    this.refresh()
                }else{
                    alert("更新验收失败")
                }
            })
        },
        btn_publish(index){
            let id = this.show_list[index].id
            let data = {"id":id,"action":"publish"}
            post(release_update_status,data).then(response=>{
                let info = JSON.stringify(response.data)
                if(info.indexOf('ok')!= -1){
                    this.$Message.success("更新上线成功")
                    this.refresh()
                }else{
                    alert("更新上线失败")
                }
            })
        },
        allow_accept(index){
            let status = this.show_list[index].status
            let userRole = localStorage.getItem('userRole')
            if(status=='待生产验证' && (userRole=='产品运营')) {
                return true
            }else{
                return false
            }
        },
        allow_publish(index){
            let status = this.show_list[index].status
            let userRole = localStorage.getItem('userRole')
            if(status=='待发布生产' && (userRole=='普通运维' || userRole=='运维')) {
                return true
            }else{
                return false
            }
        },
        allow_review(index){
            let status = this.show_list[index].status
            let review_user = this.show_list[index].review_user
            let current_user = localStorage.getItem('username')
            if(status=='待审核' && review_user==current_user){
                return true
            }else {
                return false
            }
        },
        allow_edit(index){
            let status = this.show_list[index].status
            // 草稿、重新修改 研发修改
            // 待发布生产 运维修改
            // 待生产验证  运营修改
            let userRole = localStorage.getItem('userRole')
            if(userRole=='超管'){
                return true
            }else if( (status=='草稿'||status=='重新修改') && userRole=='研发' ){
                return true
            }else if(status=='待发布生产' && (userRole=='普通运维' || userRole=='运维')) {
                return true
            }else if(status=='待生产验证' && (userRole=='产品运营')){
                return true
            }else{
                return false
            }
        },

        // 评审
        btn_review(index){
            let id = this.show_list[index].id
            let data = {"id":id}
            post(release_detail,data).then( (response) => {
                this.release_review = response.data
            })
            setTimeout(() =>{
                this.show_release_review_modal=true
            },200);
        },
        // 提交评审
        submit_review(name){
            console.log(name)
            let data = {
                'id': this.release_review.id,
                'review_form': this.review_form
            }
            post(release_review,data).then(response=>{
                let info = JSON.stringify(response.data)
                if(info.indexOf('ok')!= -1){
                    this.$Message.success("更新发布成功")
                    this.show_release_review_modal = false
                    this.refresh()
                }else{
                    alert("更新发布失败")
                }
            })
        },
        // 查询发布事项
        btn_select_release(name){
            let validate = false
            this.$refs[name].validate((valid) => {
                if (valid) validate = true
            })
            if(!validate) return

            let data = {"select_item":this.select_item}
            post(release_select,data).then( (response) => {
                 show_simple_page(this,response)
            })

        },
        // 提交发布修改
        submit_edit_release(name){
            let validate = false
            this.$refs[name].validate((valid) => {
                if (valid) validate = true
            })
            if(!validate) return
            let data = {'release':this.release_edit}

            post(release_update,data).then( (response) => {
                let info = JSON.stringify(response.data)
                if(info.indexOf('ok') != -1) {
                    this.$Message.success('更新成功')
                    this.show_edit_release_modal = false
                    this.refresh()
                }else {
                    alert("更新失败:",info)
                }
            })
        },
        // 编辑发布
        btn_edit_release(index){
            let release =  this.show_list[index]
            this.release_edit = release
            let project_name = this.release_edit.project
            this.get_leader(project_name)
            this.get_service(project_name)
            this.get_not_finished_requirement(project_name)
            this.get_not_finished_bug(project_name)
            setTimeout(() =>{
                this.show_edit_release_modal=true
            },300);
        },
        get_leader(project_name){
            let data = {"project": project_name}
            post(get_project_leader,data).then(response=>{
                console.log(response.data)
                this.project_leader = response.data
            })
        },
        // 根据项目获取未完成需求
        get_not_finished_requirement(project_name){
            let data = {"project": project_name}
            post(not_finished_requirement,data).then(response=>{
                console.log(response.data)
                this.nf_requirement_list = response.data
            })
        },
        // 根据项目获取未修复bug
        get_not_finished_bug(project_name){
            let data = {"project": project_name}
            post(not_finished_bug,data).then(response=>{
                this.nf_bug_list = response.data
            })
        },
        // 获取项目列表
        get_project(){
            post(get_project_name_list).then(response=>{
                this.project_list = response.data
            })
        },
        // 项目选择事件
        project_change(){
            this.release.service = ''
            let project_name = this.release.project
            this.get_service(project_name)
        },

        // 根据项目获取服务
        get_service(project_name){
            let data = {"project_name": project_name}
            post(get_service_by_project,data).then(response=>{
                this.service_list = response.data
            })
        },
        // 创建发布点击事件
        btn_add_release(){
            this.get_project()
            setTimeout(() =>{
                this.show_add_release_modal = true
            },200); 
        },

        submit_add_release(name){
            let validate = false
            this.$refs[name].validate((valid) => {
                if (valid) validate = true
            })
            if(!validate) return
             let data = {'release':this.release}
            post(release_add,data).then( (response) => {
                let info = JSON.stringify(response.data)
                if(info.indexOf('ok') != -1) {
                    this.$Message.success('添加成功')
                    this.show_add_release_modal = false
                    this.refresh()
                }else {
                    alert("添加失败:"+info)
                }
            })

        },
        changePage(index) {
            let _start = (index -1) * this.pageSize
            let _end = index * this.pageSize
            this.show_list = this.total_list.slice(_start,_end)
        },
        del_release(index){
            let result = confirm("确定要删除吗?")
            if(result == false) return 
            let id = this.show_list[index].id 
            let data = {"id":id }
            post(release_delete,data).then( (response) => {
                let info = JSON.stringify(response.data)
                if(info.indexOf('ok') != -1) {
                    this.$Message.success('删除成功')
                    this.refresh()
                }else {
                    alert("删除失败:",info)
                }
            })

        },
        refresh() {
            this.get_project()
            post(release_list).then( (response) => {
                show_simple_page(this,response)
            })
        }
    },
    mounted: function() {
        setTimeout(() =>{
            this.refresh();
        },200); 
    }
}
</script>
<style scoped>
    pre{
        white-space: pre-wrap!important;
        word-wrap: break-word!important;
        *white-space:normal!important;
    }
    .label_class {
        width: 100px;
        display:-moz-inline-box;
        display:inline-block;
    }
    p {
        line-height:30px;
    }
    .button_class {
        margin-bottom: 5px;
        margin-right:5px;
    }
    .check_box_class {
        width:400px;
        overflow:hidden;
    }
    .modal_footer {
        text-align:center;
        margin-bottom:5px;
        margin-top:5px
    }
</style>